package com.talking.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.talking.App;
import com.talking.presenter.MessagePresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MsgService extends Service {
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            String account=App.sp.getString("account", "");
            if (account.equals(""))return;
            MessagePresenter.queryMsg(account, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String result = response.body().string();
                    try {
                        JSONArray server = new JSONObject(result).getJSONArray("data");
                        JSONArray local;
                        String message = App.sp.getString("message", "null");
                        if (message.equals("null")){
                            local=new JSONArray();
                        }else {
                            local= new JSONArray(message);
                        }
                        JSONArray res = Utils.getNewMsgByServerMsg(local, server);
                        @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = App.sp.edit();
                        edit.putString("message",res.toString());
                        edit.apply();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            handler.postDelayed(runnable, 5000);
        }
    };
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        handler.postDelayed(runnable, 1000);
    }
}
